import React, { useEffect, useState } from 'react'
import { View,Text,Image } from '@tarojs/components'
import { AtActionSheet } from 'taro-ui'
import Taro from '@tarojs/taro'

import 'taro-ui/dist/style/components/action-sheet.scss'
import './index.scss'

export default function Package() {
  let whWays = [
    {
      "packageType": 1,
      "title": "普通包场",
      "description": "好友扫码即可领取，无需你的确认"
    },{
      "packageType": 3,
      "title": "定向包场",
      "description": "好友需要申请领取，需要你的二次确认"
    },
  ]
  const [existPopup,setexistPopup] = useState(false)
  const [customSetPopup,setcustomSetPopup] = useState(false)
  const [activity, setactivity] = useState({})
  const [haveCustom,sethaveCustom] = useState(false)
  const [cardConWidth,setcardConWidth] = useState('300rpx')
  const [cardIsActive,setcardIsActive] = useState(0)
  const [setsRanderFlag,setsetsRanderFlag] = useState(true)
  const [sets, setsets] = useState([])
  const [whWayConWidth,setwhWayConWidth] = useState('300rpx')
  const [whWayIsActive,setwhWayIsActive] = useState(0)
  const [chitIsActive,setchitIsActive] = useState(0)
  const [chits, setchits] = useState([])  //代金券数量
  const [denIsActive,setdenIsActive] = useState(0)
  const [dens, setdens] = useState([])//代金券面额

  useEffect(()=>{
    init()
  },[])

  function toRuleDetail() {
    Taro.navigateTo({
      url:'/mineSubPack/wholeCinema/wholeRuleDetail/index'
    })
  }

  function couputedWidth(width) {
    return Taro.getSystemInfoSync().screenWidth * width / 375
  }
  function couputedHeigth(heigth) {
    return Taro.getSystemInfoSync().screenHeight * heigth / 830
  }
  function isValidNumber(input) {
    const num = parseFloat(input);
    return !isNaN(num) && Number.isFinite(num) && num >= 15 && num <= 1000;
  }
  function customInputNumFun() {
    Taro.showModal({
      title: '自定义影券数量', // 标题
      editable: true, // 开启输入功能
      placeholderText: '支持15-1000', // 输入框提示文本
      success: function (res) {
        if (res.confirm) {
          if (isValidNumber(res.content)) {
            let arr = [...chits]
            if (!haveCustom) {
              sethaveCustom(true)
              // 追加
              arr.push({
                code: '111111111',
                value: res.content
              })
              setchits(arr)
            } else {
              // 覆盖最后一个
              arr[arr.length-1] = {
                code: '111111111',
                value: res.content
              }
              setchits(arr)
            }
            setchitIsActive(arr.length - 1)
          } else {
            Taro.$toast('请输入有效的数字')
          }
        }
      }
    });
  }
  function commitCustom(event){
    if(chitIsActive==-1||denIsActive==-1){
      return
    }
    setcustomSetPopup(false)
    Taro.showLoading({
      title:'生成中...'
    })
    let num = chits[chitIsActive].value
    let den = dens[denIsActive].price
    let id = dens[denIsActive].id||'custom'
    Taro.$post(`/marketing/app/package/getDiscountsByAmount`,{amount:den*num},'1',{'content-type':'application/x-www-form-urlencoded'}).then(res => {
      if (res.code === '1') {
        let arr = [...sets]
        let newSet = {
          title:'定制包场',
          num,
          denomination:den,
          id:id,
          totalAmount: res.content,
          description:''
        }
        arr.unshift(newSet)
        setsets(arr)
        setcardIsActive(0)
        setsetsRanderFlag(false)
        setTimeout(()=>setsetsRanderFlag(true),500)
      }
    })
  }
  const submitOrder = async ()=>{
    const openId = await Taro.getOpenId();
    const currCard = sets[cardIsActive]
    let setId = currCard.id
    let isCustom = false;
    if(setId=='custom'){
      setId = dens[denIsActive].couponRelationId
      isCustom = true;
    }
    
    const param = {
        appid:Taro.$mpAppid,
        // couponNum: 0,
        couponRelationId: setId, //套餐id 或 面额id
        customPackage: isCustom?1:2,
        openId: openId,
        // packageScenario: 0,
        packageType: whWays[whWayIsActive].packageType,
        payAmount: currCard.totalAmount,
        relationId: activity.id,// 活动id
        relationObject: JSON.stringify(activity) //活动的json串
    }
    Taro.showLoading({title:'加载中...'})
    await Taro.$post(`/marketing/app/package/buildPayOrder`,param,'1',{'content-type':'application/json;charset=UTF-8'}).then(res => {
        if (res.code === '1') {
          let {content} = res
          if(process.env.TARO_ENV === 'tt'){
            tt.pay({
              orderInfo: {
                order_id:content.data.orderId,
                order_token: content.data.orderToken
              },
              service: 5,
              _debug:1,
              success:res=>{
                if(res.code == 0){
                  handlePaySuccess(orderId)
                }
              },
              fail:err=>{
                Taro.$toast('取消支付')
              }
            });
            return;
          }
          if(res.content.content.extra){
            const jsonParams = JSON.parse(res.content.content.extra);
            const orderId = res.content.content.outTradeNo;
            // this.handlePaySuccess('1586100141758')
            Taro.requestPayment({
              timeStamp: jsonParams.timeStamp,
              nonceStr: jsonParams.nonceStr,
              package: jsonParams.package,
              signType: jsonParams.signType,
              paySign: jsonParams.paySign,
              success:res=>{
                handlePaySuccess(orderId)
              },
              fail:err=>{
                uni.showToast({
                  title:'支付失败',
                  icon:'none'
                })
              }
            })
          }
          }else{
            Taro.$toast(res.message)
          }
      })
  }
  function handlePaySuccess(data){  ///  支付成功
    Taro.navigateTo({
      url:`/mineSubPack/wholeCinema/wholeCinemaPlacard/index?orderId=${data}`,
    })
    return;
  }
  function navToMoviePage(){
    Taro.navigateTo({
        url:'/pages/wholeCinema/chooseMovie/index'
    })
  }
  function toMyOrder(){
    Taro.navigateTo({
        url:'/mineSubPack/wholeCinema/wholeCinemaOrder/index'
    })
  }

  ///     network
  function init() {
    //获取主题
    Taro.$get(`/marketing/app/package/getTopicDetail`,'',1).then(res=>{
      if (res.code === '1') setactivity(res.content)
    })
    //获取套餐
    Taro.$get(`/marketing/app/package/getPackages`, '', 1).then(res => {
      if (res.code === '1') setsets(res.content)
    })
    //获取数量
    Taro.$get(`/merchant/sysDicts/package-bill-num`, '', 1).then(res => {
      if (res.code === '1') setchits(res.content)
    })
    //获取金额
    Taro.$get(`/marketing/app/package/getPriceList`, '', 1).then(res => {
      if (res.code === '1') setdens(res.content)
    })
  }

  useEffect(()=>{
    setcardConWidth(((sets.length + 1) * 200) +'rpx')
  },[sets])
  useEffect(()=>{
    setwhWayConWidth((whWays.length * 350) +'rpx')
  },[whWays])
  return (
    <View className="package">
      <View id="page_container">
      <View style="background-image: linear-gradient(to bottom, rgba(255, 13, 73, 1), rgba(255, 13, 73, 0)); padding-top:24rpx; ">
        <View style="width: calc(100% - 48rpx); margin: 0 auto; background-color: #FFFFFF; border-radius: 8px; display: flex;">
          <Image style={{ 
            borderRadius: '8rpx', 
            margin: '24rpx', 
            width: couputedWidth(66) + 'px', 
            height: couputedHeigth(88) + 'px', 
            flexShrink: 0 
            }}  src={activity.imgUrl}></Image>
          <View style="margin-top: 24rpx; width: 100%;">
            <View className="info_title">{activity.title}</View>
            <View className="info_date">{activity.desc}</View>
            {activity.packageHistory!=null&&activity.packageHistory.length>0?<View style="border: 1px solid #FF84A2; padding: 16rpx; margin-right: 24rpx; border-radius: 8px; background-color: #FFFAFB; display: flex; align-items: center; justify-content: space-between; margin-top: 8rpx;" onClick={()=>{setexistPopup(true)}}  v-if="">
              <Text style="font-size: 24rpx; color: #26282A; font-weight: 400;">{activity.packageHistory[0]?.userName} 开了{activity.packageHistory[0]?.count}个包场</Text>
              <View style="font-size: 24rpx; color: #96989A; font-weight: 400;">明细 <Text className='at-icon at-icon-chevron-right' style='color:#96989A;font-size:15px'></Text></View>
            </View>:null}
          </View>
        </View>
        
        <View className="set_container">
          <View className="set_header">
            <View className="title">套餐选择</View>
            <View className="custom" onClick={()=>{setcustomSetPopup(true)}}>自定义套餐<Text className='at-icon at-icon-chevron-right' style='color:#96989A;font-size:14px'></Text></View>
          </View>
          {setsRanderFlag?
          <View className="set_card_new">
            {sets.map((item,index)=>{
              return <View className={`set_card_item_new ${cardIsActive === index?'active':''}`} style={{ marginLeft: (index !== 0 ? '12' : '0') + 'rpx' }} onClick={()=>{setcardIsActive(index)}} key={item.id}>
                <View style="color: #26282A; font-size: 28rpx;font-weight: 700;">{item.title}</View>
                <View style="color: #96989A; font-size: 24rpx;font-weight: 400;">{item.description}</View>
                <View style="color: #96989A; font-size: 24rpx;font-weight: 400; margin-top: 20rpx;">数量 {item?.num}</View>
                <View style="color: #96989A; font-size: 24rpx;font-weight: 400;">面额 ￥{item?.denomination}</View>
                <View style="color: #96989A; font-size: 24rpx;font-weight: 400; margin-top: 20rpx;">优惠价 <text style="color: #26282A;font-size: 24rpx;font-weight: 400;">￥{item?.totalAmount}</text></View>
              </View>
            })}
          </View>:null}
        </View>
      </View>
      
      <View className="whWay_container">
        <View className="set_header">
          <View className="title">包场方式</View>
          <View className="custom" onClick={()=>{toRuleDetail()}}>使用详情<Text className='at-icon at-icon-chevron-right' style='color:#96989A;font-size:14px'></Text></View>
        </View>
  
        <View style="padding-left: 24rpx; padding-right: 24rpx; padding-bottom: 24rpx; display: flex; gap: 16rpx;">
          {whWays.map((item,index)=>{
            return <View style="background-color: #FFF8F5; padding: 16rpx; width: 100%; border-radius: 8px;"  className={whWayIsActive === index?'active':''} onClick={()=>{setwhWayIsActive(index)}} key={item.id}>
              <View style="color: #26282A; font-size: 28rpx;font-weight: 700; line-height: 40rpx;">{item.title}</View>
              <View style="color: #96989A; font-size: 24rpx;font-weight: 400; line-height: 33rpx; margin-top: 6rpx;">{item.description}</View>
            </View>
          })}
        </View>
      </View>
      <View className="whole_service">
        <View className="set_header">
          <View className="title">云包场服务</View>
          <View className="custom" onClick={()=>{toRuleDetail()}}>规则说明<Text className='at-icon at-icon-chevron-right' style='color:#96989A;font-size:14px'></Text></View>
        </View>
        
        <View className="ser_body">
          <View className="icon_item" onClick={()=>{toRuleDetail()}}>
            <Image className="info-icon" src='https://taihu-finesdk.oss-cn-beijing.aliyuncs.com/fine-event/20240506/placard/ybc_0.png' mode="aspectFill"></Image>
            <Text className="icon_title">48小时领取</Text>
          </View>
          <View className="icon_item" onClick={()=>{toRuleDetail()}}>
            <Image className="info-icon" src="https://taihu-finesdk.oss-cn-beijing.aliyuncs.com/fine-event/20240506/placard/ybc_1.png" mode="aspectFill"></Image>
            <Text className="icon_title">未领取及时退</Text>
          </View>
          <View className="icon_item" onClick={()=>{toRuleDetail()}}>
            <Image className="info-icon" src="https://taihu-finesdk.oss-cn-beijing.aliyuncs.com/fine-event/20240506/placard/ybc_2.png" mode="aspectFill"></Image>
            <Text className="icon_title">未购票全额退</Text>
          </View>
          <View className="icon_item" onClick={()=>{toRuleDetail()}}>
            <Image className="info-icon" src="https://taihu-finesdk.oss-cn-beijing.aliyuncs.com/fine-event/20240506/placard/ybc_3.png" mode="aspectFill"></Image>
            <Text className="icon_title">15天有效期</Text>
          </View>
        </View>
      </View>
      <View style="width: 100%;">
        <View className="my_order">
          <View className="order_con" onClick={()=>{toMyOrder()}}>
            <View className="order_title">我的包场订单</View>
            <View className="order_icon"><Text className='at-icon at-icon-chevron-right' style='color:#7f7f7f;font-size:15px'></Text></View>
          </View>
        </View>
      </View>
  
    </View>
    <View className="footer">
      <View className="price_show">
        <Text style="font-size: 28rpx; font-weight: 400;">￥&nbsp;</Text>
        <Text style="font-size: 36rpx; font-weight: 700;">{ sets[cardIsActive]?.totalAmount }</Text>
        <View style="margin-top: -28rpx;"><Text style="font-size: 24rpx;color:#96989A;">总计优惠￥{((sets[cardIsActive]?.denomination*sets[cardIsActive]?.num)-sets[cardIsActive]?.totalAmount)}</Text></View>
      </View>
      <View ><View className="purch_btn" onClick={()=>{submitOrder()}}>提交订单</View></View>
    </View>
    
    <AtActionSheet isOpened={existPopup} onClose={()=>{setexistPopup(false)}}>
      <View className="bottom_popup">
        <View className="ex_pop_title">《{activity.title}》<Text style="font-size:28rpx; color: #26282A; font-weight: 400;"> &ensp;包场明细</Text></View>
        <View className="ex_pop_detail">
          {activity?.packageHistory?.map((item,index)=>{
            return <View className="ex_pop_item" key={index}>
              <View className="item_userName">{item.userName}</View>
              <View className="item_count">{item.count} &ensp;场</View>
            </View>
          })}
        </View>
      </View>
    </AtActionSheet>
    <AtActionSheet isOpened={customSetPopup} onClose={()=>{setcustomSetPopup(false)}} style="padding-bottom: 20rpx;">
      <View className="bottom_popup">
        <View className="cu_pop_title">自定义套餐</View> 
        <View className="cu_pop_body">
          <View className="chit_title">代金券数量</View>
          
          <View className="chit_con">
            {chits.map((item,index)=>{
              return <View className={`chit_item ${chitIsActive === index?'item_active':''}`} style="color: #26282A; font-weight: 400; font-size: 28rpx;" key={item.id} onClick={()=>{
                setchitIsActive(index)
              }} >{item.value}张</View>
            })}
            <View className="chit_item" onClick={()=>{customInputNumFun()}} style="color: #26282A; font-weight: 400; font-size: 28rpx;">自定义<Text className='at-icon at-icon-chevron-right' style='color:#000;font-size:14px'></Text></View>
          </View>
          <View className="den_title">单张面额</View> 
          <View style="font-size: 24rpx; font-weight: 400; color: #96989A; padding-left: 28rpx;  padding-top: 12rpx;">
            每笔订单仅限使用一张观赛券，订单金额未高于观赛券金额不设找零，订单金额高于观赛券金额支持现金补差价支付。
          </View>
          <View className="den_con">
            {dens.map((item,index)=>{
              return <View className={`den_item ${denIsActive === index?'item_active':''}`} key={item.couponRelationId} onClick={()=>{setdenIsActive(index)}} >￥{item.price}</View>
            })}
          </View>
        </View>
        <View className={`commitCustomBtn ${chitIsActive==-1||denIsActive==-1?'dis_commit':''}`} onClick={()=>{commitCustom()}} >{(chitIsActive==-1||denIsActive==-1)?'请先选择面额和数量':'完成我的定制'}</View>
      </View>
    </AtActionSheet>
    </View>
  )
}
